<template>
  <div class="container">
    <div class="app-container">
      <el-card>
        <div slot="header" class="clearfix">
          <span>试题录入</span>
        </div>
        <div>
          <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" size="medium" class="demo-ruleForm">
            <el-form-item label="学科:" prop="subjectID">
              <el-select v-model="ruleForm.subjectID" style="width: 400px;" placeholder="请选择学科" @change="hSelSub">
                <el-option v-for="item in subjects" :key="item.label" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="目录:" prop="catalogID">
              <el-select v-model="ruleForm.catalogID" style="width: 400px;" placeholder="请选择目录">
                <el-option v-for="item in dirList" :key="item.directoryName" :label="item.directoryName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="企业:" prop="enterpriseID">
              <el-select v-model="ruleForm.enterpriseID" style="width: 400px;" placeholder="请选择企业">
                <el-option v-for="item in comList" :key="item.number" :label="item.company" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="城市:" prop="city">
              <el-select v-model="ruleForm.province" style="width: 210px;" placeholder="请选择" @change="hSelPro">
                <el-option v-for="(item,index) in provinceList" :key="index" :value="item" />
              </el-select>
              <el-select v-model="ruleForm.city" style="width: 180px; margin-left: 10px" placeholder="请选择">
                <el-option v-for="(item,index) in cityList" :key="index" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item label="方向:" prop="direction">
              <el-select v-model="ruleForm.direction" style="width: 400px;" placeholder="请选择企业">
                <el-option v-for="item in directionType" :key="item" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item label="题型:" prop="questionType">
              <el-radio-group v-model="ruleForm.questionType">
                <el-radio v-for="item in questionType" :key="item.value" :label="item.value + ''" @change="hClickradio">{{ item.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="难度:" prop="difficulty">
              <el-radio-group v-model="ruleForm.difficulty">
                <el-radio v-for="item in difficultyType" :key="item.value" :label="item.value + ''">{{ item.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="题干:" prop="question">
              <editor v-model.trim="ruleForm.question" @blur="hQuestion" />
            </el-form-item>
            <el-form-item v-if="ruleForm.questionType !== '3'" label="选项:">
              <!-- 单选 -->
              <div v-if="ruleForm.questionType === '1'">
                <div v-for="(item,index) in ruleForm.options" :key="index" class="formCheck">
                  <el-radio v-model="isRight" :label="item.code" class="radio" @change="hRadio" />
                  <div>:</div>
                  <el-input v-model="item.title" style="width:264px" />
                  <upload v-model="item.img" />
                </div>
              </div>
              <!-- 多选 -->
              <div v-else-if="ruleForm.questionType === '2'">
                <div v-for="(item,index) in ruleForm.options" :key="index" class="formCheck">
                  <el-checkbox v-model="item.isRight" :label="item.code" class="radio" />
                  <div>:</div>
                  <el-input v-model="item.title" style="width:264px" />
                  <upload v-model="item.img" />
                </div>
              </div>
              <el-button type="danger" size="mini" :disabled="ruleForm.questionType !== '2'" @click="haddBox">+增加选项与答案</el-button>
            </el-form-item>
            <el-form-item label="解析视频:" prop="videoURL">
              <el-input v-model.trim="ruleForm.videoURL" style="width: 400px;" />
            </el-form-item>
            <el-form-item label="答案解析:" prop="answer">
              <editor v-model.trim="ruleForm.answer" @blur="hAnswer" />
            </el-form-item>
            <el-form-item label="题目备注:">
              <el-input v-model="ruleForm.remarks" type="textarea" style="width: 400px;" rows="4" />
            </el-form-item>
            <el-form-item label="试题标签:" prop="tags">
              <el-select
                v-model="tags"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请选择文章标签"
                style="width: 400px;"
                @change="hChangeTags"
              >
                <el-option
                  v-for="item in tagsLists"
                  :key="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button :type="$route.query.id ? 'success' : 'primary'" @click="hSubmit">{{ $route.query.id ? '确认修改' : '确认提交' }}</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { simple } from '@/api/hmmm/subjects.js'
import { list } from '@/api/hmmm/directorys'
import { simple as tagsSimple } from '@/api/hmmm/tags'
import { list as companyList } from '@/api/hmmm/companys'
import { provinces, citys } from '@/api/hmmm/citys'
import { questionType, direction as directionType, difficulty as difficultyType, isRightList } from '@/api/hmmm/constants'
import editor from '../components/editor.vue'
import { add, detail, update } from '@/api/hmmm/questions'
// 枚举
const isRightObj = isRightList.reduce((acc, item) => {
  acc[item.value] = item.label
  return acc
}, {})
import upload from '../components/upload.vue'
export default {
  components: {
    editor,
    upload
  },
  data() {
    return {
      questionType,
      difficultyType,
      directionType,
      tagsLists: [],
      ruleForm: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        city: '', // 地区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        options: [
          {
            isRight: false,
            code: 'A',
            title: '',
            img: ''
          },
          {
            isRight: false,
            code: 'B',
            title: '',
            img: ''
          },
          {
            isRight: true,
            code: 'C',
            title: '',
            img: ''
          },
          {
            isRight: false,
            code: 'D',
            title: '',
            img: ''
          }
        ], // 选项
        tags: '' // 标签
      },
      ascii: 69,
      isRight: '',
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: 'blur' }
        ],
        province: [
          { required: true, message: '请选择城市', trigger: 'change' }
        ],
        city: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        answer: [
          { required: true, message: '请输入答案解析', trigger: 'blur' }
        ],
        tags: [
          { required: true, message: '请选择标签', trigger: 'blur' }
        ],
        videoURL: [
          { required: true, message: '请上传视频', trigger: 'blur' }
        ]
      },
      subjects: [], // 学科列表
      dirList: [], // 目录列表
      comList: [], // 企业列表
      provinceList: [], // 城市列表
      cityList: [], // 地区列表
      tags: []
    }
  },
  async created() {
    this.loadSubSimple()
    this.loadCompanyList()
    this.provinces()
    // 判断是否点击编辑进来的
    const id = this.$route.query.id
    if (id) {
      const res = await detail({ id, isNext: false })
      // 数据格式转化
      res.data.options.forEach(item => {
        item.isRight = isRightObj[item.isRight]
        if (item.isRight) {
          this.isRight = item.code
        }
      })
      // 解决排序错误问题
      res.data.options.sort((a, b) => {
        return a.code.charCodeAt() - b.code.charCodeAt()
      })
      this.ascii = res.data.options.length + 65
      this.ruleForm = res.data
      this.tagsLists = res.data.tags.split(',')
      this.tags = this.tagsLists
    }
  },
  methods: {
    // 提交
    hSubmit() {
      // 判断是否是选择题,并且是否有选选项
      if (this.ruleForm.questionType !== '3') {
        const res = this.ruleForm.options.every(item => {
          return item.isRight === false
        })
        if (res) {
          this.$message.error('选项至少选择一个正确答案')
          return false
        }
      }
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) {
          this.$message.error('请输入完整信息')
          return false
        }
        this.$route.query.id ? this.doEdit() : this.doAdd()
      })
    },
    // 添加题目
    async doAdd() {
      try {
        const res = await add(this.ruleForm)
        console.log(res)
        this.$message.success('试题录入成功')
        this.$router.push('/questions/list')
      } catch (error) {
        console.log(error)
        this.$message.error('试题录入失败')
      }
    },
    // 修改题目
    async doEdit() {
      try {
        const res = await update({ ...this.ruleForm, id: this.$route.query.id })
        console.log(res)
        this.$message.success('修改成功')
        this.$router.push('/questions/list')
      } catch (error) {
        console.log(error)
        this.$message.error('修改失败')
      }
    },
    haddBox() {
      this.ruleForm.options.push({
        isRight: false,
        code: String.fromCharCode(this.ascii++),
        title: '',
        img: ''
      })
    },
    // 选择题型清空选项
    hClickradio() {
      this.ruleForm.options.forEach((item) => {
        item.isRight = false
      })
    },
    // 获取学科简单列表
    async loadSubSimple() {
      const res = await simple()
      this.subjects = res.data
    },
    // 选择学科,获取目录
    hSelSub(cur) {
      this.ruleForm.catalogID = ''
      this.ruleForm.tags = []
      this.loadDirList()
      this.loadTagList()
    },
    // 获取目录列表
    async loadDirList() {
      const dirList = await list(this.ruleForm)
      this.dirList = dirList.data.items
    },
    // 获取标签列表
    async loadTagList() {
      const tagList = await tagsSimple({
        subjectID: this.ruleForm.subjectID
      })
      this.tagsLists = tagList.data.map(item => (item = item.label))
    },
    // 获取企业列表
    async loadCompanyList() {
      const res = await companyList({ page: 1, pagesize: 10000 })
      this.comList = res.data.items
    },
    // 初始化城市
    provinces() {
      this.provinceList = provinces()
    },
    // 选择城市后初始化地区
    hSelPro(cur) {
      // 1.清空地区输入框
      this.ruleForm.city = ''
      this.cityList = citys(cur)
    },
    hRadio(a) {
      this.ruleForm.options.forEach(item => {
        if (item.code === a) {
          item.isRight = true
          return
        }
        item.isRight = false
      })
    },
    hChangeTags() {
      this.ruleForm.tags = this.tags.join(',')
    },
    hQuestion() {
      this.$refs.ruleForm.validateField('question')
    },
    hAnswer() {
      this.$refs.ruleForm.validateField('answer')
    }

  },
  // 阻止误操作
  beforeRouteUpdate(to, from, next) {
  }
}
</script>
<style scoped>
::v-deep .ql-editor {
  height: 200px !important;
}
.formCheck {
  display: flex;
  align-items: center;
}
.radio {
  margin-right: 6px;
}

::v-deep .el-checkbox__label {
  width: 16px;
}
</style>
